/** 
 * 地址管理
 * 
 */
import { Button, List } from 'antd-mobile';
import React from 'react';
import style from './style.module.scss';
import Panel from 'components/Panel';
import lazy from 'router/utils/lazy'
import { Switch, Route, RouteChildrenProps, withRouter } from 'react-router-dom';
import history from 'router/history'
import { decorator } from 'grey-react-box';
// import { district } from 'antd-mobile-demo-data';
import { server } from 'server';

const district = require('constant/area.json');

const Item = List.Item;
const Brief = Item.Brief;

const AddressEdit = lazy(() => import('page/AddressEdit'));

export default decorator<any, RouteChildrenProps>(withRouter)(props => {

    const { pathname } = props.location

    const { list, del, setDefault, update } = useAddress();

    return (
        <>
            <Panel className={style.body} >
                <div className={style.cont} >
                    <List renderHeader={() => '收获地址'} className="my-list">
                        {list.map(e => {
                            return (
                                <Item key={e.id} wrap extra={
                                    <>
                                        <Button size="small" type="primary" onClick={() => { history.push(`${pathname}/edit`, { ...e, userAddress: e.userAddress }) }} >编辑</Button>
                                        {e.defaultAddress === 'FALSE' && <Button size="small" onClick={() => { setDefault(e.id) }} style={{ marginTop: 10 }} >默认</Button>}
                                        <Button size="small" type="warning" onClick={() => { del(e.id) }} style={{ marginTop: 10 }} >删除</Button>
                                    </>
                                } >
                                    {districtToString(e.userAddress, district, '')} {e.userDetailAddress}
                                    <Brief>{e.userPhone}<br />{e.userName}</Brief>
                                </Item>
                            )
                        })}
                    </List>
                </div>
                <Button type="primary" className={style.butt} onClick={() => { history.push(`${pathname}/edit`) }} >添加地址</Button>
            </Panel >
            <Switch>
                <Route path="*/edit" render={() => <AddressEdit onChange={update} />} />
            </Switch>
        </>
    )
})

/**  地址的 hook */
const useAddress = () => {

    const [list, setList] = React.useState<any[]>([])

    const update = React.useCallback(async () => {
        const url = `/medicine/address/getAll`;
        const ajax = await server.get(url).end();
        if (ajax.err) return;
        try {
            setList(ajax.res.body.data.map(e => ({ ...e, userAddress: JSON.parse(e.userAddress) })));
        } catch (error) {
            setList([])
        }
    }, [])

    const del = React.useCallback(async id => {
        const url = `/medicine/address/delete`;
        const ajax = await server.get(url, { dataId: id }).end();
        if (ajax.err) return;

        update();
    }, [update])

    const setDefault = React.useCallback(async id => {
        const url = `/medicine/address/setDefault`;
        const ajax = await server.get(url, { dataId: id }).end();
        if (ajax.err) return;

        update()
    }, [update])

    React.useEffect(() => {
        update();
    }, [update])

    return { list, del, setDefault, update }
}

const districtToString = (e: any[], list: any[], str: string) => {
    try {
        const ev = e ? e.slice() : [];
        if (ev && ev.length > 0) {
            const it = list.filter(v => v.value === ev[0])[0];
            if (it) {
                ev.shift();
                return districtToString(ev, it.children, `${str} ${it.label}`);
            } else {
                return str;
            }
        }
        return str;
    } catch (error) {
        return ''
    }
}
